package com.dhy.takeaway.service;

import com.dhy.takeaway.dao.LoginDao;
import com.dhy.takeaway.dao.StoreDao;
import com.dhy.takeaway.entity.Store;
import com.dhy.takeaway.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Service
public class LoginService {
    @Autowired
    LoginDao loginDao;
    @Autowired
    StoreDao  storeDao;

    public User loginSuccess(String username){
        return loginDao.findUserByName(username);
    }

    public boolean userNameIsExist(String username){
        User user = loginDao.findUserByName(username);
        return user != null;
    }

    public boolean register(User user){
        if(userNameIsExist(user.getUsername())){
            return false;
        }

        String id = UUID.randomUUID().toString();
        user.setId(id);
        if (loginDao.insertUser(user) == 1) {
            Store store = new Store();
            store.setId(UUID.randomUUID().toString());
            store.setUserId(id);
            store.setCreateTime(new Date());
            store.setUpdateTime(new Date());
            store.setState("停营");
            return storeDao.insertStore(store) > 0;
        }
        return false;
    }

    public boolean checkPass(User user){
        User u = loginDao.findUserById(user.getId());
        if (u != null) {
            if (u.getPassword().equals(user.getPassword())) {
                return true;
            }
        }
        return false;
    }

    public boolean changePass(Map<String, String> map){
        User user = new User();
        user.setId(map.get("id"));
        user.setPassword(map.get("oldPass"));
        if (this.checkPass(user)) {
            user.setPassword(map.get("password"));
            if (loginDao.updateUser(user) > 0) {
                return true;
            }
        }
        return false;
    }

    public boolean updateStore(Store store){
        store.setUpdateTime(new Date());
        if (storeDao.updateStore(store) > 0) {
            return true;
        }
        return false;
    }

    public Store findStore(String userId){
        return storeDao.selectStore(userId);
    }
}
